package com.kpl.kplstzble.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.kpl.kplstzble.R;
import com.kpl.kplstzble.adapter.DataAdapter;
import com.kpl.kplstzble.entity.HistoryData;
import com.kpl.kplstzble.utils.DBUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class HistoryDataFragment extends Fragment{

    private View mapLayout;
    private static HistoryDataFragment fragment=null;
    public static Fragment newInstance(){
        if(fragment==null){
            synchronized(HistoryDataFragment.class){
                if(fragment==null){
                    fragment=new HistoryDataFragment();
                }
            }
        }
        return fragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
        if (mapLayout == null) {
            mapLayout = inflater.inflate(R.layout.history_data, null);
            Toolbar toolbar = mapLayout.findViewById(R.id.toolbar);
            //设置图标
            //在android studio里面创建图标会放到mipmap下
            //如果是自己做的放在drawable下面的就是R.drawable.xxxx
            toolbar.setNavigationIcon(R.mipmap.back1);
           /* setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/
            toolbar.setNavigationOnClickListener(view -> {
                HomeFragment homeFragment = new HomeFragment();
                FragmentManager fm = getActivity().getSupportFragmentManager();
                    /*fm.beginTransaction()
                            .replace(R.id.fl_content, dataDetailFragment)
                            .commit();*/
                fm.beginTransaction().replace(R.id.fl_content,homeFragment)
                        .commit();
                //getActivity().finish();
            });
            new Thread(
                    () -> {
                        ArrayList<HistoryData> gethistorydata = DBUtils.gethistorydata();
                        Message msg= new Message();
                        msg.what=0;
                        msg.obj=gethistorydata;
                        Handler.sendMessage(msg);
                    }
            ).start();
        }
        return mapLayout;
    }
    private Handler Handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                ExpandableListView mExpandableListView = mapLayout.findViewById(R.id.expandablelistview);
                List<String> groupList = new ArrayList<>();
                List<List<HistoryData>> childList = new ArrayList<>();
                HashMap<String, List<HistoryData>> dataListHashMap = new HashMap<>();
                HashMap<String, Double> everydaydataHashMap = new HashMap<>();//统计每天总亩数
                if(msg.obj instanceof ArrayList<?>){
                    for (Object o:(List<?>)msg.obj){
                        HistoryData historyData = (HistoryData) o;
                        String date = historyData.getDate();
                        String daydate = date.split(" ")[0];
                        Set<String> keys = dataListHashMap.keySet();
                        DecimalFormat df = new DecimalFormat("0.00");//保留2位小数
                        if(keys.contains(daydate)){
                            dataListHashMap.get(daydate).add(historyData);
                            everydaydataHashMap.put(daydate,Double.valueOf(df.format(everydaydataHashMap.get(daydate)+Double.parseDouble(historyData.getMunum()))));
                        }else {
                            List<HistoryData> historyDatalist = new ArrayList<>();
                            historyDatalist.add(historyData);
                            dataListHashMap.put(daydate,historyDatalist);
                            everydaydataHashMap.put(daydate,Double.valueOf(df.format(Double.parseDouble(historyData.getMunum()))));
                        }
                    }
                }
                // 4. 使用 Lambda 表达式遍历 HashMap
                dataListHashMap.forEach((key, value) -> {
                    System.out.println(key);
                    List<HistoryData> childList1 = new ArrayList<>();
                    groupList.add(key);
                    System.out.println(value);
                    childList1.addAll(value);
                    childList.add(childList1);
                });
                DataAdapter dataAdapter = new DataAdapter(getContext(),groupList,everydaydataHashMap, childList/*,deleteClick*/);
                mExpandableListView.setAdapter(dataAdapter);

                //一级点击监听
                mExpandableListView.setOnGroupClickListener((parent, v, groupPosition, id) -> {
                    Toast.makeText(getContext(), "你点击了：" + groupList.get(groupPosition), Toast.LENGTH_SHORT).show();
                    //如果你处理了并且消费了点击返回true,这是一个基本的防止onTouch事件向下或者向上传递的返回机制
                    return false;
                });

                //二级点击监听
                mExpandableListView.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {
                    Toast.makeText(getContext(), "你点击了：" + childList.get(groupPosition).get(childPosition).getId(), Toast.LENGTH_SHORT).show();
                    HistoryData object = childList.get(groupPosition).get(childPosition);
                    System.out.println(object.getId());
                    DataDetailFragment dataDetailFragment = new DataDetailFragment(object);
                    FragmentManager fm = getActivity().getSupportFragmentManager();
                    fm.beginTransaction().replace(R.id.fl_content,dataDetailFragment)
                            .addToBackStack(null).commit();
                            //.setCustomAnimations(R.anim.fragment_enter, R.anim.fragment_exit).commit();
                    //如果你处理了并且消费了点击返回true
                    return false;
                });
            }
        }
    };
}
